<template>
  <div class="app-container">
    <el-container style="min-height:700px;height: 100%;">
      <!-- 左侧流程数据模块-->
      <el-card class="box-card" shadow="never" >
        <el-main style="padding: 0">
          <div style='position: relative;'>
            <el-tabs tab-position="top" v-model="activeName" @tab-click="handleClick">
              <!--表单信息-->
              <el-tab-pane name="1">
                <span slot="label"><i class="el-icon-form"></i> 表单信息</span>
                <el-col :span="16" :offset="4">
                  <v-form-render v-if="renderForm" ref="vFormRef"/>
                  <component v-else :is="formCompName" ref="vFormRef"></component>
                </el-col>
              </el-tab-pane>

              <!--流程流转记录-->
              <el-tab-pane name="2">
                <span slot="label"><i class="el-icon-flow-record"></i> 流转记录</span>
                <flow-record v-if="flowRecordOpen" :flowRecordList="flowRecordList" />
              </el-tab-pane>
              <!--流程图-->
              <el-tab-pane name="3">
                <span slot="label"><i class="el-icon-flow"></i> 流程图</span>
                <bpmn-viewer v-if="flowDataOpen" :flowData="flowData" :procInsId="taskForm.procInsId"/>
              </el-tab-pane>
            </el-tabs>
            <el-button style='position: absolute;right:195px;top:5px;' type="warning" size="mini" @click="saveDraft">暂 存</el-button>
            <el-button style='position: absolute;right:120px;top:5px;' type="success" size="mini" @click="handleOpenDraft">草稿箱</el-button>
<!--            <el-button style='position: absolute;right:120px;top:5px;' size="mini" type="info"  @click="handlePrint">打印</el-button>-->
            <el-button style='position: absolute;right:60px;top:5px;' size="mini" type="danger" @click="goBack">关闭</el-button>
            <el-tooltip class="item" effect="dark" placement="top">
              <template slot="content">{{designer ? '收起' : '展开'}}</template>
              <el-button style='position: absolute;right:10px;top:5px;' size="mini" :icon="designer ? 'el-icon-d-arrow-right':'el-icon-d-arrow-left'" @click="togglePanel"/>
            </el-tooltip>
          </div>
        </el-main>
      </el-card>

      <!--右侧流程处理模块-->
      <el-card shadow="never" :style="designer?'width: 50%':'width: 0'">
        <template slot="header">
           <i class="el-icon-s-check"/> 任务申请
          <el-tag effect="plain" size="small">当前节点:{{ taskForm.taskName }}</el-tag>
        </template>
            <el-form
              label-position="top"
              label-width="100px"
              :model="taskForm"
              :rules="rules"
              size="mini"
              ref="taskFormRef"
              style="max-width: 460px"
            >
              <el-form-item label="抄送人">
                <el-button round style="margin-right: 5px;margin-bottom: 5px" size="mini" type="primary" icon="el-icon-plus" @click="copyUserOpen = true">添加抄送</el-button>
                <el-tag
                  style="margin-right: 5px;"
                  v-for="user in selectCopyUserList"
                  :key="user.userId"
                  closable
                  effect="plain"
                  size="small"
                  @close="removeCopy(user)">
                  {{user.nickName}}
                </el-tag>
              </el-form-item>
              <el-form-item label="申请备注" prop="comment">
                <el-input type="textarea" :rows="3" v-model="taskForm.comment" placeholder="请填写申请备注"/>
              </el-form-item>
              <el-form-item label="操作" required>
                <!--如果设计流程时未配置按钮信息,那么此时给定一个固定的审批按钮,避免流程任务卡在当前任务节点,无法正常运转-->
                <template v-if="taskButtonList.length > 0">
                  <el-button class="button-line" plain v-for="button in taskButtonList" :key="button.id" :icon="button.icon" :size="button.size" :type="button.type" v-on:click="handleButtonClick(button.click)">
                    {{ button.label }}
                  </el-button>
                </template>
                <template v-else>
                  <el-button plain icon="el-icon-check" size="mini" type="primary" @click="handleComplete">申 请</el-button>
                </template>
              </el-form-item>
        </el-form>
      </el-card>
    </el-container>

    <!--抄送人员-->
    <el-dialog title="抄送人员" :visible.sync="copyUserOpen" width="60%" :close-on-press-escape="false" :destroy-on-close="true" :show-close="false">
      <flow-users v-if="copyUserOpen" :selectData="taskForm.checkedCopyUser" @handleAssignSelect="copyUserSelect"></flow-users>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="copyUserOpen = false">取 消</el-button>
        <el-button size="small" type="primary" @click="submitCopySelect">确 定</el-button>
      </div>
    </el-dialog>


    <!--重新申请任务-->
    <el-dialog
      title="重发任务"
      :visible.sync="taskSubmitOpen"
      width="'65%'"
      :close-on-press-escape="false"
      :destroy-on-close="true"
      append-to-body
    >
      <el-form label-position="top" label-width="100px">
        <template v-for="(item, index) in nextAssignList">
          <el-form-item v-if="item.dataType === 'dynamic'" :key="index">
            <label slot="label"><i style="color:red;">*&nbsp; </i> 任务接收 ({{item.nextNodeName}})</label>
            <el-button round style="margin-right: 5px;margin-bottom: 5px" size="mini" type="primary" icon="el-icon-plus" @click="changeNextAssign(item)">选择任务接收</el-button>
            <el-tag
              style="margin-right: 5px;"
              v-for="assign in item.selectAssignList"
              :key="assign.id"
              closable
              size="small"
              @close="removeAssign(assign, item.nextNodeId)">
              {{assign.name}}
            </el-tag>
          </el-form-item>
        </template>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="info" size="mini" @click="taskSubmitOpen = false">取 消</el-button>
        <el-button type="primary" size="mini" @click="submitTask">确 认</el-button>
      </span>
    </el-dialog>

    <!--流程任务接收人-->
    <el-dialog
      title="选择任务接收"
      :visible.sync="completeOpen"
      :width="currentType === 'dept' ? '30%' : '65%'"
      :before-close="cancelAssignSelect"
      :close-on-press-escape="false"
      :destroy-on-close="true"
      append-to-body
    >
      <component v-if="completeOpen" :is="currentComponent" :selectData="selectDataMap[nextNodeId]" @handleAssignSelect="handleAssignSelect"/>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="cancelAssignSelect">取 消</el-button>
        <el-button size="mini" type="primary" @click="submitSelect">确 认</el-button>
      </span>
    </el-dialog>

    <!--委托任务-->
    <el-dialog :title="delegateTaskTitle" :visible.sync="delegateTaskOpen" width="60%" append-to-body>
        <flow-assignee v-if="delegateTaskOpen" :userType="'delegate'" @handleDelegateUser="delegateUserSelect"/>
        <span slot="footer" class="dialog-footer">
          <el-button size="small" @click="delegateTaskOpen = false">取 消</el-button>
          <el-button size="small" type="primary" @click="delegateTaskComplete">确 定</el-button>
        </span>
    </el-dialog>

    <!--转办任务-->
    <el-dialog :title="transferTaskTitle" :visible.sync="transferTaskOpen" width="60%" append-to-body>
        <flow-assignee v-if=" transferTaskOpen" :userType="'transfer'" @handleTransferUser="transferUserSelect"/>
        <span slot="footer" class="dialog-footer">
          <el-button size="small" @click="transferTaskOpen = false">取 消</el-button>
          <el-button size="small" type="primary" @click="transferTaskComplete">确 定</el-button>
        </span>
    </el-dialog>

    <!--打印预览-->
    <el-dialog
      :visible.sync="printVisible"
      title="打印预览"
      width="70%"
      append-to-body
    >
      <printer v-if="printVisible" :printData="printData"></printer>
    </el-dialog>

    <!--草稿信息-->
    <el-drawer
      title="草稿信息"
      size="45%"
      :visible.sync="draftOpen"
      :close-on-press-escape="false"
      :destroy-on-close="true"
      direction="rtl"
      append-to-body
    >
      <el-table v-loading="loading" :data="flowDraftList">
        <el-table-column label="主键" align="center" prop="id" />
        <el-table-column label="草稿名称" align="center" prop="draftName" />
        <el-table-column label="创建时间" align="center" prop="createTime" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-s-promotion"
              @click="handleUseDraft(scope.row)"
            >使用</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDeleteDraft(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        layout="prev, pager, next"
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getDraftList"
      />
    </el-drawer>
  </div>
</template>

<script>
import {flowRecord} from "@/api/flowable/finished";
import FlowAssignee from '@/components/Flow/Task/Assignee';
import FlowUsers from '@/components/Flow/Task/User';
import FlowRole from '@/components/Flow/Task/Role';
import FlowDept from '@/components/Flow/Task/Dept';
import FlowPost from '@/components/Flow/Task/Post';
import {flowXmlAndNode} from "@/api/flowable/definition";
import {
  refillTask,
  getNextFlowNodeByRefill,
  delegateTask,
  transferTask,
  flowTaskButton,
  refillFlowFormData
} from "@/api/flowable/todo";
import {draftList, saveDraftByTask, delDraft} from "@/api/flowable/process";
import BpmnViewer from '@/components/Process/viewer';
import Printer from '@/components/Process/printer';
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {StrUtil} from "@/utils/StrUtil";
import {assignSelect} from "@/views/flowable/common/AssignUtils";
import FlowRecord from "@/components/Process/record";

export default {
  name: "RefillTask",
  components: {
    FlowRecord,
    BpmnViewer,
    FlowAssignee,
    FlowUsers,
    FlowRole,
    Printer,
    FlowDept,
    FlowPost
  },
  props: {},
  data() {
    return {
      eventName: "click",
      // 流程数据
      flowData: {},
      taskButtonList: [],
      activeName: '1',
      flowRecordOpen: false,
      flowDataOpen: false,

      flowRecordList: [], // 流程流转数据
      // 表单校验
      rules: {
        comment: [
          {required: true, message: '请填写申请备注', trigger: 'blur'}
        ]
      },
      taskForm: {
        taskName: null, // 任务节点
        comment: "", // 意见内容
        procInsId: "", // 流程实例编号
        instanceId: "", // 流程实例编号
        deployId: "",  // 流程定义编号
        taskId: "",// 流程任务编号
        procDefId: "",  // 流程编号
        targetKey: "",
        flowParam: "", // 流程变量参数
        variables: {},
        checkedAssignMap: {},
        checkedCopyUser: null,
        copyUser: [],
      },
      completeOpen: false,
      checkAssign: false, // 是否展示人员选择模块
      selectDataList: [], // 选择数据列表
      selectCopyDataList:[], // 选择数据列表
      selectAssignList:[], // 选择审核列表
      // 区分多实例任务
      flowType: null,
      // 委托任务
      delegateTaskTitle: '',
      delegateTaskOpen: false,
      // 转办任务
      transferTaskTitle: '',
      transferTaskOpen: false,
      // 打印
      printData: {},
      printVisible: false,
      // 抄送人
      designer: true,
      copyUserOpen: false,
      selectCopyUserList: [],
      renderForm: true, // 是否渲染在线表单
      formCompName: '', // 路由表单组件名称
      currentType: '', // 用于确定当前显示的组件
      nextNodeId: '', // 下一节点ID
      nextAssignList: [], // 后续审批
      selectDataMap: {},
      taskSubmitOpen: false,

      // 草稿信息
      draftOpen: false,
      loading: true, // 是否显示遮罩层
      flowDraftList: [], // 草稿内容
      total: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
    };
  },
  computed: {
    currentComponent() {
      return this.currentType ? `flow-${this.currentType}` : '';
    }
  },
  created() {
    if (this.$route.query) {
      this.taskForm = this.$route.query;
      this.taskForm.checkedAssignMap = {};
      this.getFlowTaskForm();
      this.getFlowTaskButton();
      // 打印
      this.printData.procInsId = this.taskForm.procInsId;
    }
  },
  methods: {
    handleClick(tab, event) {
      if (tab.name === '2') {
        // 切换tab时避免重复请求接口
        if (!this.flowRecordOpen) {
          this.getFlowRecordList();
        }
      }else if (tab.name === '3') {
        if (!this.flowDataOpen) {
          this.flowDataOpen = true;
          flowXmlAndNode(this.taskForm).then(res => {
            this.flowData = res.data;
          })
        }
      }
    },

    // 获取流程节点表单
    getFlowTaskForm() {
      if (this.taskForm.taskId) {
        // 从流程变量中获取填写的表单数据
        refillFlowFormData(this.taskForm).then(res => {
          if (res.data.formType === 'route') {
            // 加载路由表单
            this.loadRouteForm(res.data);
          } else {
            // 加载在线表单
            this.loadOnlineForm(res.data);
          }
        });
      }
    },
    // 加载路由表单
    loadRouteForm(data) {
      this.renderForm = false;
      this.formCompName = data.formContent;
      this.$nextTick(() => {
        this.$refs.vFormRef.setFormData(data.flowData, false);
      });
    },
    // 加载在线表单
    loadOnlineForm(data) {
      this.renderForm = true;
      this.$nextTick(() => {
        this.$refs.vFormRef.setFormJson(data.formContent);
        this.$nextTick(() => {
          this.$refs.vFormRef.setFormData(data.flowData);
        });
      });
    },

    /** 流程流转记录 */
    getFlowRecordList() {
      const that = this
      flowRecord(this.taskForm).then(res => {
        that.flowRecordList = res.data.flowList;
        that.flowRecordOpen = true;
      }).catch(res => {
        this.goBack();
      })
    },

    /** 流程节点按钮 */
    getFlowTaskButton() {
      if (this.taskForm.taskId) {
        flowTaskButton(this.taskForm).then(res => {
          this.taskButtonList = res.data;
        });
      }
    },

    /** 委托任务 */
    handleDelegate() {
      this.delegateTaskTitle = "委托人选择";
      this.delegateTaskOpen = true;
    },

    // 提交处理委托任务
    delegateTaskComplete() {
      this.$refs["taskFormRef"].validate(valid => {
        if (valid) {
          delegateTask(this.taskForm).then(response => {
            this.$modal.msgSuccess(response.msg);
            this.goBack();
          });
          this.delegateTaskTitle = "";
          this.delegateTaskOpen = false;
        }
      });
    },

    /** 转办任务 */
    handleTransfer() {
      this.transferTaskTitle = "转办人选择";
      this.transferTaskOpen = true;
    },

    /** 提交处理转办任务 */
    transferTaskComplete() {
      this.$refs["taskFormRef"].validate(valid => {
        if (valid) {
          transferTask(this.taskForm).then(response => {
            this.$modal.msgSuccess(response.msg);
            this.goBack();
          });
          this.transferTaskTitle = "";
          this.transferTaskOpen = false;
        }
      });
    },

    // 获取流程中的下一个任务节点
    nextFLowNode() {
      // 调用API获取下一个流程节点
      getNextFlowNodeByRefill(this.taskForm).then(res => {
        const dataList = res?.data || [];
        this.nextAssignList = dataList.map(data => ({
          nextNodeId: data.nextNodeId,
          nextNodeName: data.nextNodeName,
          dataType: data.dataType,
          currentType: data.type === 'multiInstance'? 'users': data.type,
          flowType: data.type,
          flowParam: data.flowParam,
          selectAssignList: [],
          approval: data?.approval || '',
          userList: data?.userList || [],
          roleList: data?.roleList || [],
          deptList: data?.deptList || [],
          postList: data?.postList || [],
        }));

        this.nextAssignList.forEach(data => {
          // 设置任务审批人/组 ,再次发起申请则不需要选择任务接收人
          if (StrUtil.isNotBlank(data.approval)) {
            // 设置任务审批人/组
            this.updateSelectAssignList(data, data.currentType);
            this.taskForm.checkedAssignMap[data.nextNodeId] = data.approval;
          }
        })

        // 选择任务接收人或直接提交任务
        if (this.nextAssignList.length > 0){
          this.taskSubmitOpen = true;
        } else {
          this.submitTask();
        }
      })
    },

    // 更新任务审批
    updateSelectAssignList(data, currentType) {
      if (["role", "dept", "post"].includes(currentType)) {
        data.selectAssignList = data[`${currentType}List`].map(item => ({id: item[`${currentType}Id`], name: item[`${currentType}Name`], nodeId: data.nextNodeId}));
      } else if (["assignee", "users"].includes(currentType)) {
        data.selectAssignList = data.userList.map(item => ({id: item.userId, name: item.nickName, nodeId: data.nextNodeId}));
      }
      // 设置审批人数据回显
      if ("assignee" === currentType || "dept" === currentType) {
        this.selectDataMap[data.nextNodeId] = data.selectAssignList.map(item => item.id).join(',') || '';
      } else {
        this.selectDataMap[data.nextNodeId] = data.selectAssignList
      }
    },

    // 打开任务审批弹窗
    handleComplete(){
      this.$refs.vFormRef.getFormData().then(formData => {
        //  获取表单数据并赋值到流程变量对象中
        this.taskForm.variables = {...formData};
        this.$refs["taskFormRef"].validate(valid => {
          if (valid) {
            this.nextFLowNode();
          }
        })
      }).catch(error => {
        console.log(error);
      })
    },

    /** 审批流程任务 */
    submitTask() {
      this.$refs.vFormRef.getFormData().then(formData => {
        // 获取表单数据并赋值到表单数据对象中
        this.taskForm.formData = {...formData};
        //  获取表单数据并赋值到流程变量对象中
        this.taskForm.variables = {...formData};
        // 如果需要选择任务接收者但是没有选择，则提示错误信息，否则设置流程变量
        const that = this;
        for (let i = 0; i < that.nextAssignList.length; i++) {
          const nextAssign = that.nextAssignList[i];
          if (nextAssign.dataType === 'dynamic' && StrUtil.isBlank(that.taskForm.checkedAssignMap[nextAssign.nextNodeId])) {
            that.$modal.msgError("请选择" + nextAssign.nextNodeName + "节点任务接收者信息!");
            return;
          }
          // 处理多实例任务,多实例任务的接收者是一个数组
          let checkedValue = that.taskForm.checkedAssignMap[nextAssign.nextNodeId];
          if (nextAssign.flowType && nextAssign.flowType === 'multiInstance') {
            checkedValue = checkedValue.split(',');
          }
          this.$set(that.taskForm.variables, nextAssign.flowParam, checkedValue);
        }
        // 验证表单数据是否合法
        this.$refs["taskFormRef"].validate(valid => {
          if (valid) {
            // 提交任务
            this.submitRefillTask();
          }
        })
      }).catch(error => {
        console.log(error)
        // 如果获取表单数据失败，则提示错误信息
        this.$modal.msgError("请完善表单信息!");
      })
    },

    /** 提交审批任务 */
    submitRefillTask() {
      refillTask(this.taskForm).then(response => {
        this.$modal.msgSuccess(response.msg);
        this.completeOpen = false;
        this.goBack();
      });
    },

    /** 委托用户 */
    delegateUserSelect(selection) {
      if (selection) {
        this.taskForm.userId = selection.userId.toString();
        this.taskForm.userName = selection.nickName;
      }
    },

    /** 转办用户 */
    transferUserSelect(selection) {
      if (selection) {
        this.taskForm.userId = selection.userId.toString();
        this.taskForm.userName = selection.nickName;
      }
    },

    // 用户选中数据
    copyUserSelect(selection) {
      if (selection) {
        this.selectCopyDataList = JSON.parse(JSON.stringify(selection));
      }
    },

    // 处理信息选中数据
    handleAssignSelect(selection) {
      if (selection) {
        // 将选中的数据覆盖selectDataList
        this.selectDataList = JSON.parse(JSON.stringify(selection));
      }
    },

    // 保存选中的数据
    submitSelect() {
      const that = this;
      that.nextAssignList.forEach(nextAssign => {
        if (nextAssign.nextNodeId === that.nextNodeId) {
          nextAssign.selectAssignList = JSON.parse(JSON.stringify(assignSelect(nextAssign.currentType, nextAssign.nextNodeId, that.selectDataList)));
          const checkedAssign = nextAssign.selectAssignList.map(item => item.id).join(',') || '';
          that.taskForm.checkedAssignMap[nextAssign.nextNodeId] = checkedAssign;
          if ("assignee" === nextAssign.currentType || "dept" === nextAssign.currentType) {
            that.selectDataMap[nextAssign.nextNodeId] = checkedAssign;
          } else {
            that.selectDataMap[nextAssign.nextNodeId] = nextAssign.selectAssignList
          }
        }
      });
      this.cancelAssignSelect();
    },

    // 取消任务审批数据
    cancelAssignSelect(){
      this.completeOpen = false;
    },

    // 移除任务接收人
    removeAssign(assign, nextNodeId) {
      const that = this;
      that.$confirm("确认移除该任务接收者吗？", "提示", {
        confirmButtonText: "确 认",
        cancelButtonText: "取 消"
      }).then(() => {
        that.nextAssignList.forEach(nextAssign => {
          const index = nextAssign.selectAssignList.findIndex(item => item.id === assign.id && item.nodeId === nextNodeId);
          if (index !== -1) {
            nextAssign.selectAssignList.splice(index, 1);
            const checkedAssign = nextAssign.selectAssignList.map(item => item.id).join(',') || '';
            that.taskForm.checkedAssignMap[nextAssign.nextNodeId] = checkedAssign;
            if ("assignee" === nextAssign.currentType || "dept" === nextAssign.currentType) {
              that.selectDataMap[nextAssign.nextNodeId] = checkedAssign;
            } else {
              that.selectDataMap[nextAssign.nextNodeId] = nextAssign.selectAssignList
            }
          }
        });
      }).catch(() => console.info("操作取消"));
    },

    // 保存抄送选中的数据
    submitCopySelect() {
      // 如果抄送用户弹窗打开
      if (this.copyUserOpen) {
        // 深拷贝选中的数据
        this.selectCopyUserList = this.selectCopyDataList.map(item => Object.assign({}, item));
        // 将选中的用户id存入taskForm的copyUser属性中
        this.taskForm.copyUser = this.selectCopyUserList.map(item => item.userId);
        // 将选中的用户id以逗号分隔的字符串形式存入taskForm的checkedCopyUser属性中
        this.taskForm.checkedCopyUser = this.selectCopyUserList;
      }
      // 关闭抄送用户弹窗状态
      this.copyUserOpen = false;
    },

    // 移除抄送人员
    removeCopy(user) {
      // 弹出确认框
      this.$confirm("确认移除该抄送人员吗？", "提示", {
        confirmButtonText: "确 认",
        cancelButtonText: "取 消"
      }).then(() => {
        const index = this.selectCopyUserList.findIndex(item => item.userId === user.userId);
        if (index !== -1) {
          // 从抄送人员列表中移除该用户
          this.selectCopyUserList.splice(index, 1);
          // 更新表单中的抄送人员列表
          this.taskForm.copyUser = this.selectCopyUserList.map(item => item.userId);
          // 更新表单中的选中抄送人员
          this.taskForm.checkedCopyUser = this.selectCopyUserList;
        }
      }).catch(() => console.info("操作取消"));
    },

    /** 动态绑定操作按钮的点击事件 */
    handleButtonClick(method) {
      // 参考地址: https://blog.csdn.net/qq_29777207/article/details/118574628
      this[method]();
    },

    /** 打印预览 */
    handlePrint() {
      this.printData.procDefName = this.taskForm.procDefName;
      this.printVisible = true;
    },

    /** 隐藏面板*/
    togglePanel() {
      this.designer = !this.designer;
    },


    /** 选择任务接收 */
    changeNextAssign(item){
      this.currentType = item.currentType;
      this.nextNodeId = item.nextNodeId;
      this.completeOpen = true;
    },


    // 打开草稿箱
    handleOpenDraft() {
      this.draftOpen = true;
      this.getDraftList();
    },

    // 获取草稿箱列表
    getDraftList() {
      this.loading = true;
      this.queryParams.taskId = this.taskForm.taskId;
      draftList(this.queryParams).then(res => {
        this.flowDraftList = res.data.records;
        this.total = res.data.total;
        this.loading = false;
      })
    },

    // 保存草稿
    saveDraft() {
      this.$refs.vFormRef.getFormData().then(formData => {
        // 获取表单数据并赋值到表单数据对象中
        this.taskForm.formData = {...formData};
        //  获取表单数据并赋值到流程变量对象中
        this.taskForm.variables = {...formData};
        saveDraftByTask(this.taskForm).then(() => {
          this.$modal.msgSuccess('保存成功');
          this.goBack();
        })
      })
    },

    // 使用草稿
    handleUseDraft(row) {
      this.$refs.vFormRef.setFormData(JSON.parse(row.formContent));
      this.draftOpen = false;
    },

    // 删除草稿
    handleDeleteDraft(row) {
      this.$modal.confirm('是否确认删除编号为"' + row.id + '"的草稿？').then(function () {
        return delDraft(row.id);
      }).then(() => {
        this.getDraftList();
        this.$modal.msgSuccess('删除成功');
      }).catch(() => {});
    },

    /** 返回页面 */
    goBack() {
      // 关闭当前标签页并返回上个页面
      const obj = {path: "/task/mine", query: {t: Date.now()}};
      this.$tab.closeOpenPage(obj);
    },
  },
};
</script>
<style lang="scss" scoped>
.test-form {
  margin: 15px auto;
  width: 800px;
  padding: 15px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both
}

.box-card {
  width: 100%;
}

.el-tag + .el-tag {
  margin-left: 10px;
}

.my-label {
  background: #E1F3D8;
}

.el-dialog-div{
  height: 60vh;
  overflow: auto;
}

.button-line {
  margin-top: 5px;
  margin-left: 0;
  margin-right: 5px;
}
</style>
